<template>
    <div class="koi-flex">
        <KoiCard>

            <el-descriptions class="margin-top" title="角色信息" :column="4" border>

                <template #extra>
                    <el-tooltip content="刷新" placement="top">
                        <el-button circle icon="refresh" @click="handleRefresh()" />
                    </el-tooltip>

                    <el-tooltip content="修改" placement="top">
                        <el-button circle icon="Edit" @click="handleEdit()" />
                    </el-tooltip>
                </template>

                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            角色名称
                        </div>
                    </template>
                    {{ useHead.name }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            是否开放注册
                        </div>
                    </template>
                    {{ useHead.allowRegister ? "是" : "否" }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            是否后台访问
                        </div>
                    </template>
                    {{ useHead.isAdminRole ? "是" : "否" }}
                </el-descriptions-item>

                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            角色标识
                        </div>
                    </template>
                    <el-tag size="small">{{ useHead.tag }}</el-tag>
                </el-descriptions-item>

                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            权限级别
                        </div>
                    </template>
                    {{ useHead.level }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            服务角色标识
                        </div>
                    </template>
                    {{ serviceRoleTag !== "" ? serviceRoleTag : "暂无" }}
                </el-descriptions-item>
            </el-descriptions>

            <div class="header">

                <div class="title">
                    角色权限
                </div>

                <el-input v-model="filterText" placeholder="请输入需要查找的权限API" style="margin-bottom: 16px;width: 400px;" />

                <el-scrollbar height="550px">

                    <el-tree ref="updateRoleTree" :empty-text="emptyText" v-loading="!apiTree" :data="apiTree"
                        show-checkbox default-expand-all node-key="id" highlight-current :props="treeProps"
                        :filter-node-method="filterNode">
                        <template #default="{ node, data }">
                            <span>{{ node.label }}</span>
                            <span style="color: #409eff;margin-left: 10px;">{{ data.url }}</span>
                            <span style="color: #909399;margin-left: 10px;">{{ data.method }}</span>
                        </template>
                    </el-tree>

                </el-scrollbar>

            </div>

        </KoiCard>
    </div>
</template>

<script setup lang="ts" name="roleDetail">
import { getAllApi, getRole, getRoleService } from "@/api/system/role";
import { useRoute } from "vue-router";
import { koiMsgError, koiMsgWarning } from '@/utils/koi';
import { formatTree } from '@/utils/tree';

import { onMounted, ref, reactive, watch } from "vue";

import { ElTree } from 'element-plus'
import router from "@/routers";

const route = useRoute();

let useHead = ref<any>({})
let serviceRoleTag = ref<any>('')
const fetchRoleData = async (id: any) => {
    try {
        const res: any = await getRole(id);
        useHead.value = res
    } catch (error) {
        koiMsgError('获取角色详情失败，请稍后再试。');
    }
};

const fetchRoleTags = async (id: any) => {
    try {
        const res: any = await getRoleService(id);
        if (JSON.stringify(res) == "{}") return;
        let str = "";
        let serverNames = Object.keys(res);
        serverNames.forEach(item => {
            if (!str) str += item + "(" + Object.keys(res[item])[0] + ")";
            else str += "," + item + "(" + Object.keys(res[item])[0] + ")";
        });
        serviceRoleTag.value = str;
        console.log('serviceRoleTag.value', serviceRoleTag.value);
    } catch (error) {
        koiMsgError('获取角色服务标识失败，请稍后再试。');
    }
};

const apiTree = ref<any>();
const checked = ref<any>();

const treeProps = reactive({
    label: "name",
    children: "children",
    disabled: "disabled"
});

const filterText = ref()

const updateRoleTree = ref<InstanceType<typeof ElTree>>()

watch(filterText, (val) => {
    updateRoleTree.value!.filter(val)
})

const emptyText = ref('')

const filterNode = (value: string, data: any, node: any) => {
    if (!value) return true; // 如果没有搜索词，则显示所有节点

    // 检查标签、URL和方法是否包含搜索词
    const labelMatch = node.label.indexOf(value) !== -1;
    const urlMatch = data.url && data.url.indexOf(value) !== -1;
    const methodMatch = data.method && data.method.indexOf(value) !== -1;

    if (!labelMatch && !urlMatch && !methodMatch) {
        let parentNode = node.parent;
        let labels = [node.label];
        let level = 1;

        // 收集所有父节点的标签
        while (level < node.level && parentNode) {
            labels.push(parentNode.label);
            parentNode = parentNode.parent;
            level++;
        }

        // 检查是否有任一父级标签匹配
        const hasParentMatch = labels.some((label) => label.indexOf(value) !== -1);

        // 更新emptyText如果没有任何匹配项
        if (!hasParentMatch && !urlMatch && !methodMatch && emptyText.value === '') {
            emptyText.value = '暂无数据';
        }

        return hasParentMatch || urlMatch || methodMatch;
    }

    return labelMatch || urlMatch || methodMatch;
};

const fetchApiList = async () => {
    try {

        apiTree.value = null;
        checked.value = [];

        const res: any = await getAllApi();
        apiTree.value = formatTree(res.data, true);
        res.data.forEach((i: any) => {
            useHead.value.api.forEach((o: any) => {
                if (i.url === o.url && i.method === o.method) (checked.value as any).push(i.id);
            });
        });
        (updateRoleTree.value as any).setCheckedKeys(checked.value);
    } catch (error) {
        koiMsgError('获取所有接口列表失败，请稍后再试。');
    }
};

const handleRefresh = async () => {
    await fetchRoleData(route.params.id);
    await fetchRoleTags(route.params.id);
    await fetchApiList();
};

onMounted(() => {
    handleRefresh();
});

const handleEdit = () => {
    console.log('编辑');
    koiMsgWarning('暂未实现，敬请期待。');
    router.push({
        path: "/system/role/edit",
    });
};
</script>

<style scoped lang="scss">
.header {
    display: flex;
    margin-top: 16px;
    flex-direction: column;
}

.title {
    color: #303133;
    font-size: 16px;
    margin-bottom: 16px;
    font-weight: bold;
}
</style>